import codecs
import json
import uuid
import emoji
import logging
from tqdm import tqdm

from django.views import View
from django.http.request import HttpRequest
from django.http import JsonResponse
from django.utils import timezone
from django.db.models import Q

from .models import TicketModel as TicketModel_Class
from .utils import idmi_nlp_tool
from .utils import mapping_brand_series

ComplaintModel = TicketModel_Class()


def generate_unique_id():
    unique_id = uuid.uuid4().hex
    return unique_id


sourceId_list = [
    "complaint_12365auto",
    "complaint_315auto",
    "complaint_315qc",
    "complaint_aqsiqauto",
    "complaint_autohome",
    "complaint_qctsw",
    "complaint_qiche365",
    "complaint_qichemen",

    "forum_autohome",
    "forum_dongchedi",
    "forum_pcauto",
    "forum_xcar",
    "forum_yiche",
]


class StoreComplaint(View):
    '''
        store the complaint sent
        {
            "sourceId": "complaint_12365auto",
            "url": "http://m.12365auto.com/zlts/20231031/1041369.shtml",
            "_url_unique": "/zlts/20231031/1041369.shtml",
            "source_web_origin": "12365auto",
            "save_source_image": "yes",
            "info_category": "complaint",
            "title": "上汽大众途昂X变速箱过不平路面有咔咔异响",
            "text": "车辆行驶减速带，时候变速箱出现咔咔异响，去经销商检查告知没有问题，这几天行驶观察还是有咔咔异响声音。",
            "brand_src": "上汽大众",
            "series_src": "途昂X",
            "model_src": "2023款 380TSI 四驱 尊崇豪华版",
            "image_urls": "[]"
        }
    '''

    def post(self, request: HttpRequest) -> JsonResponse:
        sourceId = request.POST.get('sourceId')
        if sourceId in sourceId_list:
            ComplaintModel.sourceId = sourceId
            ComplaintModel.uuid = generate_unique_id()
            ComplaintModel.source_web_origin = request.POST.get('source_web_origin')
            ComplaintModel.save_source_image = request.POST.get('save_source_image')
            ComplaintModel.info_category = request.POST.get('info_category')

            ComplaintModel.URL = request.POST.get('url')[:400]
            ComplaintModel.url_unique = request.POST.get('_url_unique')[:400]

            datetime_now = timezone.now()
            ComplaintModel.create_time = datetime_now
            ComplaintModel.update_time = datetime_now

            __title_zh = request.POST.get('title')[:400]
            __text_zh = request.POST.get('text')[:1000]
            ComplaintModel.title_zh = __title_zh
            ComplaintModel.text_zh = __text_zh
            __title_zh = self.clean_sentence(__title_zh)
            __text_zh = self.clean_sentence(__text_zh)

            temp__brand_src = request.POST.get('brand_src', '')
            FLAG_translate_needed = True
            # for __ in [
            #     '大众', 'VW', 'vw',
            #     '特斯拉', 'Tesla', 'TESLA',
            #     '小鹏', 'Xpeng',
            #     '埃安', 'AION',
            #     '赛力斯', 'AITO',
            #     '比亚迪', 'BYD',
            # ]:
            #     if __ in temp__brand_src:
            #         FLAG_translate_needed = True
            #         break
            nlp_res = idmi_nlp_tool.response(
                title=__title_zh,
                text=__text_zh,
                if_translate=FLAG_translate_needed,
                sourceId=sourceId
            )
            ComplaintModel.FLAG_function_group_problem = nlp_res['FLAG_function_group_problem']
            ComplaintModel.FLAG_ncvqs = False

            ComplaintModel.title_en = nlp_res['title_en']
            ComplaintModel.text_en = nlp_res['text_en']
            ComplaintModel.FLAG_translate_to_en = nlp_res['translate_success']

            function_group_problem_zh = nlp_res['function_group_problem_zh'][:5]
            function_group_problem_en = nlp_res['function_group_problem_en'][:5]
            Ncvqs_labels = []

            ComplaintModel.function_group_problem = json.dumps(function_group_problem_zh, ensure_ascii=False)
            ComplaintModel.function_group_problem_en = json.dumps(function_group_problem_en, ensure_ascii=False)
            ComplaintModel.ncvqs = json.dumps(Ncvqs_labels, ensure_ascii=False)

            __save_images = request.POST.get('save_source_image')

            # if __save_images == 'yes':
            #     image_urls = request.POST.get('image_urls')
            #     image_urls = json.loads(image_urls)[:5]
            #     ComplaintModel.image_url = json.dumps(image_urls, ensure_ascii=False)
            # else:
            ComplaintModel.image_url = ''

            # preprocess the brand_src and series_src and model_src
            __brand_src = request.POST.get('brand_src', '')
            __series_src = request.POST.get('series_src', '')
            __model_src = request.POST.get('model_src', '')

            if sourceId in [
                'forum_autohome', 'forum_dongchedi', 'forum_pcauto', 'forum_xcar', 'forum_yiche'
            ]:
                ComplaintModel.brand_src = __brand_src
                ComplaintModel.series_src = __series_src
                ComplaintModel.model_src = __model_src
                ComplaintModel.brand = __brand_src
                ComplaintModel.series = __series_src
                ComplaintModel.model = __model_src
                ComplaintModel.FLAG_brand_model_convert = True
                ComplaintModel.save()
                return JsonResponse({'status': 200})
            else:
                ComplaintModel.brand_src = __brand_src[:40]
                ComplaintModel.series_src = __series_src[:40]
                ComplaintModel.model_src = __model_src[:40]
                brand, series = mapping_brand_series.mapping_get(
                    sourceId,
                    __brand_src,
                    __series_src
                )
                ComplaintModel.brand = brand
                ComplaintModel.series = series
                if len(brand) and len(series):
                    ComplaintModel.FLAG_brand_model_convert = True
                else:
                    ComplaintModel.FLAG_brand_model_convert = False
                ComplaintModel.save()
                return JsonResponse({'status': 200})
        else:
            return JsonResponse({'status': 500})

    def clean_sentence(self, sentence):
        if len(sentence):
            sentence = sentence. \
                replace('\r', ''). \
                replace('\n', ''). \
                replace('\t', ''). \
                replace('"', ''). \
                replace("'", ""). \
                replace('  ', ""). \
                replace('“', ' '). \
                replace('”', ' ')
            try:
                sentence = emoji.demojize(sentence)
            except:
                sentence = sentence
            return sentence
        else:
            return ''


#
# class UpdateComplaint(View):
#     def post(self, request):
#         return JsonResponse({'status': 200})
#
# uuid_str = request.POST.get('uuid_str')
# url_unique = request.POST.get('url_unique')
# title_zh = request.POST.get('title_zh')
# text_zh = request.POST.get('text_zh')
# title_en = request.POST.get('title_en')
# text_en = request.POST.get('text_en')
# source_web_origin = request.POST.get('source_web_origin')
# sourceId = request.POST.get('sourceId')
# series_src = request.POST.get('series_src')
# series = request.POST.get('series')
# save_source_image = request.POST.get('save_source_image')
# function_group_problem = json.loads(request.POST.get('function_group_problem'))
# function_group_problem_en = json.loads(request.POST.get('function_group_problem_en'))
# ncvqs_1 = request.POST.get('ncvqs_1')
# ncvqs_2 = request.POST.get('ncvqs_2')
# model_src = request.POST.get('model_src')
# model = request.POST.get('model')
# language_type_from_platform = request.POST.get('language_type_from_platform')
# info_category = request.POST.get('info_category')
# image_url = request.POST.get('image_url')
# create_time = request.POST.get('create_time')
# update_time = request.POST.get('update_time')
# FLAG_function_group_problem = request.POST.get('FLAG_function_group_problem')
# brand_src = request.POST.get('brand_src')
# brand = request.POST.get('brand')
# already_request_img_content = request.POST.get('already_request_img_content')
# URL = request.POST.get('URL')
# FLAG_translate_to_en = request.POST.get('FLAG_translate_to_en')
# FLAG_ncvqs = request.POST.get('FLAG_ncvqs')
# FLAG_brand_model_convert = request.POST.get('FLAG_brand_model_convert')
#
#
# ComplaintModel.uuid = uuid_str
# ComplaintModel.create_time = create_time
# ComplaintModel.update_time = create_time
# ComplaintModel.info_category = info_category
# ComplaintModel.source_web_origin = source_web_origin
# ComplaintModel.save_source_image = save_source_image
# ComplaintModel.URL = URL
# ComplaintModel.sourceId = sourceId
# ComplaintModel.FLAG_function_group_problem = FLAG_function_group_problem
# ComplaintModel.function_group_problem = json.dumps(function_group_problem, ensure_ascii=False)
# ComplaintModel.function_group_problem_en = json.dumps(function_group_problem_en, ensure_ascii=False)
# ComplaintModel.FLAG_ncvqs = FLAG_ncvqs
# ComplaintModel.ncvqs = json.dumps([], ensure_ascii=False)
# ComplaintModel.brand_src = brand_src
# ComplaintModel.series_src = series_src
# ComplaintModel.model_src = model_src
# ComplaintModel.FLAG_brand_model_convert = FLAG_brand_model_convert
# ComplaintModel.brand = brand
# ComplaintModel.series = series
# ComplaintModel.model = model
# ComplaintModel.url_unique = url_unique
# ComplaintModel.language_type_from_platform = language_type_from_platform
# ComplaintModel.title_zh = title_zh
# ComplaintModel.text_zh = text_zh
# ComplaintModel.FLAG_translate_to_en = FLAG_translate_to_en
# ComplaintModel.title_en = title_en
# ComplaintModel.text_en = text_en
# ComplaintModel.image_url = image_url
# ComplaintModel.already_request_img_content = already_request_img_content
# ComplaintModel.save()
#





class UpdateComplaint(View):
    def get(self, request):
        return JsonResponse({'status': 200})
        #
        # end_date = timezone.now()
        # start_date = end_date - timezone.timedelta(hours=24 * 60,
        #                                            minutes=0, seconds=0)
        # _res_list = TicketModel_Class.objects.filter(
        #     Q(
        #         Q(FLAG_function_group_problem=True)
        #     ) &
        #     Q(create_time__range=(start_date, end_date))
        # ).all().values(
        #     'uuid',
        #     'brand', 'series',
        #     'function_group_problem_en'
        # )
        # print('------------')
        # print(len(_res_list))
        # print('------------')
        # for _res in tqdm(_res_list):
        #     try:
        #         uuid_str = _res['uuid']
        #         brand = _res['brand']
        #         series = _res['series']
        #         _function_group_problem_en = _res['function_group_problem_en']
        #         if brand in [
        #             'SVW', 'FAW-VW', 'VWA', 'Audi', 'Xpeng',
        #         ]:
        #             function_group_problem_en = []
        #             _function_group_problem_en = json.loads(_function_group_problem_en)
        #             for _d in _function_group_problem_en:
        #                 _content_list = _d['content_list']
        #                 content_list = []
        #                 function_group = _d['function_group']
        #                 problem = _d['problem']
        #                 sentiment = _d['sentiment']
        #                 # [{"content_list": ["大家交流大众探岳目前行驶28000公里。我想知道为啥以上80码90码就有异响，80码以下没有异响，超过95异响就小了"],
        #                 #   "function_group": "Front and rear axles and suspension system", "problem": "Abnormal wheel noise",
        #                 #   "sentiment": "negative"},
        #                 #  {"content_list": ["大家交流大众探岳目前行驶28000公里。我想知道为啥以上80码90码就有异响，80码以下没有异响，超过95异响就小了"],
        #                 #   "function_group": "Body accessories and electrical appliances", "problem": "Abnormal body noise",
        #                 #   "sentiment": "negative"}]
        #                 for _content in _content_list:
        #                     _content_en = idmi_nlp_tool._translate_util_zh2en(
        #                         sentence=_content
        #                     )['en']
        #                     content_list.append(_content_en)
        #                     function_group_problem_en.append({
        #                         'content_list': content_list,
        #                         'function_group': function_group,
        #                         'problem': problem,
        #                         'sentiment': sentiment
        #                     })
        #             function_group_problem_en = json.dumps(function_group_problem_en, ensure_ascii=False)
        #             TicketModel_Class.objects.filter(uuid=uuid_str).update(
        #                 function_group_problem_en=function_group_problem_en,
        #                 update_time=timezone.now()
        #             )
        #             print(uuid_str)
        #     except:
        #         ...
        # return JsonResponse({'status': 200})

        #         translate_res = idmi_nlp_tool._translate_util_zh2en(
        #             title=title_zh, text=text_zh
        #         )
        #         print(translate_res)
        #         info_1 = TicketModel_Class.objects.filter(uuid=uuid).update(
        #             FLAG_translate_to_en=True,
        #             title_en=translate_res['title_en'],
        #             text_en=translate_res['text_en'],
        #             update_time=timezone.now()
        #         )
        #         print(title_zh)
        #         print(text_zh)
        #         print(_res['uuid'])
        #
        #
        # return JsonResponse({'status': 200})


#
# with codecs.open(filename='/root/03_backend/idmi-backend-v5/idmi_backend/Quality-trans.json',
#                  mode='r', encoding='utf-8') as fr:
#     quality_dict = json.load(fr)
#
# # 导入之前的 IDMI 的全量数据
# class UpdateComplaint(View):
#     def post(self, request):
#         uuid_str = request.POST.get('uuid')
#         create_time = request.POST.get('create_time')
#         update_time = request.POST.get('update_time')
#         info_category = request.POST.get('info_category')
#         source_web_origin = request.POST.get('source_web_origin')
#         save_source_image = request.POST.get('save_source_image')
#         sourceId = request.POST.get('sourceId')
#         llm_quality = request.POST.get('llm_quality')
#
#         FLAG_function_group_problem = request.POST.get('FLAG_function_group_problem')
#         function_group_problem = request.POST.get('function_group_problem', [])
#         function_group_problem = json.loads(function_group_problem)
#
#
#         FLAG_ncvqs = request.POST.get('FLAG_ncvqs')
#         ncvqs = request.POST.get('ncvqs')
#         ncvqs = json.loads(ncvqs)
#         brand_src = request.POST.get('brand_src')
#         series_src = request.POST.get('series_src')
#         model_src = request.POST.get('model_src')
#         FLAG_brand_model_convert = request.POST.get('FLAG_brand_model_convert')
#         brand = request.POST.get('brand')
#         series = request.POST.get('series')
#         model = request.POST.get('model')
#         url_unique = request.POST.get('url_unique')
#         language_type_from_platform = request.POST.get('language_type_from_platform')
#         title_zh = request.POST.get('title_zh')
#         text_zh = request.POST.get('text_zh')
#         FLAG_translate_to_en = request.POST.get('FLAG_translate_to_en')
#         title_en = request.POST.get('title_en')
#         text_en = request.POST.get('text_en')
#         image_url = request.POST.get('image_url')
#         image_url = json.loads(image_url)
#         already_request_img_content = request.POST.get('already_request_img_content')
#
#         function_group_problem_en = []
#         if len(function_group_problem):
#             for fp in function_group_problem:
#
#                 content_list = fp['content_list']
#                 function_group_en = quality_dict[fp['function_group']]
#                 problem_en = quality_dict[fp['problem']]
#                 sentiment_en = quality_dict[fp['sentiment']]
#                 function_group_problem_en.append({
#                     'content_list' : content_list,
#                     'function_group' : function_group_en,
#                     'problem' : problem_en,
#                     'sentiment' : sentiment_en
#                 })
#
#         ComplaintModel.uuid = uuid_str
#         ComplaintModel.create_time = create_time
#         ComplaintModel.update_time = update_time
#         ComplaintModel.info_category = info_category
#         ComplaintModel.source_web_origin = source_web_origin
#         ComplaintModel.save_source_image = save_source_image
#         ComplaintModel.sourceId = sourceId
#         ComplaintModel.FLAG_function_group_problem = FLAG_function_group_problem
#         ComplaintModel.function_group_problem = json.dumps(function_group_problem, ensure_ascii=False)
#         ComplaintModel.FLAG_ncvqs = FLAG_ncvqs
#         ComplaintModel.ncvqs = json.dumps(ncvqs, ensure_ascii=False)
#         ComplaintModel.brand_src = brand_src
#         ComplaintModel.series_src = series_src
#         ComplaintModel.model_src = model_src
#         ComplaintModel.FLAG_brand_model_convert = FLAG_brand_model_convert
#         ComplaintModel.brand = brand
#         ComplaintModel.series = series
#         ComplaintModel.model = model
#         ComplaintModel.url_unique = url_unique
#         ComplaintModel.language_type_from_platform = language_type_from_platform
#         ComplaintModel.title_zh = title_zh
#         ComplaintModel.text_zh = text_zh
#         ComplaintModel.FLAG_translate_to_en = FLAG_translate_to_en
#         ComplaintModel.title_en = title_en
#         ComplaintModel.text_en = text_en
#         ComplaintModel.image_url = json.dumps(image_url, ensure_ascii=False)
#         ComplaintModel.already_request_img_content = already_request_img_content
#         ComplaintModel.function_group_problem_en = json.dumps(function_group_problem_en, ensure_ascii=False)
#         ComplaintModel.save()
#         return JsonResponse({'status': 200})


#
# # 对齐其中的function_group_problem_en中的数据
# import time
# from tqdm import tqdm
#
# class UpdateComplaint(View):
#     def post(self, request):
#         D = TicketModel_Class.objects.all().values(
#             'uuid',
#             'function_group_problem'
#         )
#         for d in tqdm(D):
#             uuid = d['uuid']
#             function_group_problem = json.loads(d['function_group_problem'])
#             function_group_problem_en = []
#             if len(function_group_problem):
#                 for fp in function_group_problem:
#                     content_list = fp['content_list']
#                     function_group_en = quality_dict[fp['function_group']]
#                     problem_en = quality_dict[fp['problem']]
#                     sentiment_en = quality_dict[fp['sentiment']]
#                     function_group_problem_en.append({
#                         'content_list' : content_list,
#                         'function_group' : function_group_en,
#                         'problem' : problem_en,
#                         'sentiment' : sentiment_en
#                     })
#
#             TicketModel_Class.objects.filter(uuid=uuid).update(
#                 function_group_problem_en=json.dumps(function_group_problem_en, ensure_ascii=False)
#             )
#         return JsonResponse({'status': 200})


'''
# 这个方法是旧的方法，感觉没啥卵用之后也是，just save it here
class UpdateComplaint(View):
    def post(self, request):
        line = request.POST.get('line')
        line = json.loads(line)
        # {'uuid': '0001c50d73864f91ae0b5caf327ad5aa', 
        # 'create_time': '2024-10-10', 
        # 'update_time': '2024-10-10', 
        # 'info_category': 'forum', 
        # 'source_web_origin': 'pcauto', 
        # 'save_source_image': 'yes', 
        # 'URL': 'https://m.pcauto.com.cn/bbs/topic-17570559.html', 
        # 'sourceId': 'forum_pcauto', 'FLAG_function_group_problem': 0, 
        # 'function_group_problem': '[]',
        # 'FLAG_ncvqs': 1, 'ncvqs': '["Engine in general unspecified"]',
        # 'brand_src': 'FAW', 'series_src': 'Golf', 
        # 'model_src': '', 'FLAG_brand_model_convert': 1, 'brand': 'FAW-VW', 
        # 'series': 'Golf', 'model': '',
        # 'url_unique': '17570559@@FAW@@Golf', 
        # 'language_type_from_platform': 'zh', 
        # 'title_zh': '大众高尔夫GTITCR在奥地利首次亮相', 
        # 'text_zh': '最近大众高尔夫GTITCR在奥地利的ReifnitzamWrthersee首次亮相。特别版是TCR比赛系列高尔夫GTI的街头版。在动力方面，涡轮增压2.0', 
        # 'FLAG_translate_to_en': 0, 
        # 'title_en': '', 'text_en': '',
        # 'image_url': '[]', 'already_request_img_content': 0}
        create_time = line['create_time']
        update_time = line['update_time']
        info_category = line['info_category']
        source_web_origin = line['source_web_origin']
        save_source_image = line['save_source_image']
        URL = line['URL']
        sourceId = line['sourceId']
        FLAG_function_group_problem = line['FLAG_function_group_problem']
        function_group_problem = line['function_group_problem']
        FLAG_ncvqs = line['FLAG_ncvqs']
        ncvqs = line['ncvqs']
        brand_src = line['brand_src']
        series_src = line['series_src']
        model_src = line['model_src']
        FLAG_brand_model_convert = line['FLAG_brand_model_convert']
        brand = line['brand']
        series = line['series']
        model = line['model']
        url_unique = line['url_unique']
        language_type_from_platform = line['language_type_from_platform']
        title_zh = line['title_zh']
        text_zh = line['text_zh']
        FLAG_translate_to_en = line['FLAG_translate_to_en']
        title_en = line['title_en']
        text_en = line['text_en']
        image_url = line['image_url']
        already_request_img_content = line['already_request_img_content']

        ComplaintModel.uuid = generate_unique_id()
        ComplaintModel.create_time = create_time
        ComplaintModel.update_time = update_time
        ComplaintModel.info_category = info_category
        ComplaintModel.source_web_origin = source_web_origin
        ComplaintModel.save_source_image = save_source_image
        ComplaintModel.URL = URL
        ComplaintModel.sourceId = sourceId
        ComplaintModel.FLAG_function_group_problem = FLAG_function_group_problem
        ComplaintModel.function_group_problem = function_group_problem
        ComplaintModel.FLAG_ncvqs = FLAG_ncvqs
        ComplaintModel.ncvqs = ncvqs
        ComplaintModel.brand_src = brand_src
        ComplaintModel.series_src = series_src
        ComplaintModel.model_src = model_src
        ComplaintModel.FLAG_brand_model_convert = FLAG_brand_model_convert
        ComplaintModel.brand = brand
        ComplaintModel.series = series
        ComplaintModel.model = model
        ComplaintModel.url_unique = url_unique
        ComplaintModel.language_type_from_platform = language_type_from_platform
        ComplaintModel.title_zh = title_zh
        ComplaintModel.text_zh = text_zh
        ComplaintModel.FLAG_translate_to_en = FLAG_translate_to_en
        ComplaintModel.title_en = title_en
        ComplaintModel.text_en = text_en
        ComplaintModel.image_url = image_url
        ComplaintModel.already_request_img_content = already_request_img_content
        ComplaintModel.save()
        return JsonResponse({'status': 200})

'''
